<template lang="pug">
  .CreateCommercialWagesModal
    Modal(
      v-model="isShowCreateCommercialWagesModal"
      :title="actionType === 'view' ? '查看商保待遇' : (actionType === 'edit' ? '修改商保待遇' : '新增商保待遇')"
      class-name="vertical-center-modal"
      width="900"
    )
      .clearfix
        Form.ivu-row.has-rules-item2(ref="formData" :model="formData" :rules="rules" :label-width="120")
          FormItem.form-item.ivu-col(v-for="(item, index) of formItem" :label="item.label" :key="index" :class="item.style" :prop="item.prop")
            template(v-if="item.type === 'input'")
              Input(v-model="formData[item.model]" :placeholder="actionType === 'view' ? '未填写' : item.placeholder" :disabled="actionType === 'view' || item.isDisabled" clearable)
            template(v-if="item.type === 'select'")
              Select(v-if="item.fn" v-model="formData[item.model]" :placeholder="actionType === 'view' ? '未填写' : item.placeholder" :disabled="actionType === 'view' || item.isDisabled" clearable filterable @on-change="listenCall(item.fn, item.model, $event)")
                Option(v-for="(c_item, c_index) of arrListDown[item.options]" :key="c_index" :value="c_item.value") {{c_item.label}}
              Select(v-else v-model="formData[item.model]" :placeholder="actionType === 'view' ? '未填写' : item.placeholder" :disabled="actionType === 'view' || item.isDisabled" clearable filterable)
                Option(v-for="(c_item, c_index) of arrListDown[item.options]" :key="c_index" :value="c_item.value") {{c_item.label}}
            template(v-if="item.type === 'switch'")
              i-switch(v-model="formData[item.model]" :disabled="actionType === 'view' || item.isDisabled")
            template(v-if="item.type === 'interval'")
              DatePicker.pull-left.interval-date-140(v-model="formData[item.model1]" :placeholder="actionType === 'view' ? '未填写' : item.placeholder1" type="date" @on-change="handleChangeDatePicker(item.model1, $event)" :disabled="actionType === 'view' || item.isDisabled")
            template(v-if="item.type === 'fujian'")
              Poptip(trigger="hover" title="合同附件" :disabled="arrListDown[item.options].length == 0")
                div(slot="content" )
                  .u-d-info(v-for="(item, index) in arrListDown[item.options]" :key="index" @click="handleDownLoad(item)") {{item.name}}
                Button(:disabled="arrListDown[item.options].length == 0") 查看
        Table.hasTitle-table.beautiful-table(:columns="thead" :data="rankList" :stripe="true" height="200" v-if='this.showTable')

      .clearfix(slot="footer")
        Button(type="text" @click="cancel") 取消
        Button(v-if="actionType !== 'view'" type="primary" @click="handleSave" :loading="!isCanSubmit") 保存
</template>

<script>
import config from '@/config'
import { Common } from '@/utils/common.js'
import dataApi from '@/api/data.js'
import { TreatmentApi } from '@/api/Treatment.api.js'
import { TreatmentEnjoyManageApi } from '@/api/TreatmentEnjoyManage.api.js'
import { TreatmentBasicsTypeApi } from '@/api/TreatmentBasicsType.api.js'
import { EmployeesApi } from '@/api/Employees.api.js'
import _cloneDeep from 'clone-deep'
import { RankThead } from '../tableHead.js'
const baseUrl = process.env.NODE_ENV === 'development' ? config.baseUrl.dev : config.baseUrl.pro

export default {
  name: 'CreateCommercialWagesModal',

  props: [],

  watch: {
  },

  computed: {
  },

  data () {
    return {
      thead:_cloneDeep(RankThead),
      isShowCreateCommercialWagesModal: false,
      isCreate: true, 
      actionType: 'view',
      wagesId: '',
      formData: {
        id: '',
        enjoyType: 3,
        customerId: '',
        employeeID: '',
        treatmentTypeId: '', // 待遇参数ID
        insuredTypeId: '', // 参保险种
        employeeIdCardNo: '',
        personalCode: '',
        socialSecurityId: '',
        areaGUID: '',
        areaName: '',
        add_DeclareDate: '',
        reduce_DeclareDate: '',
        declareSalary: ''
      },
      formItem: [
        { type: 'select', label: '客户名称：', placeholder: '请选择客户名称', prop: 'customerId', model: 'customerId', style: 'ivu-col-span-11', options: 'companyList', fn: 'customerIdChange', isDisabled: false },
        { type: 'select', label: '员工：', placeholder: '请选择员工', prop: 'employeeID', model: 'employeeID', style: 'ivu-col-span-13', options: 'employeeList', fn: 'selectChange', isDisabled: true },
        // { type: 'select', label: '参保险种：', placeholder: '请选择参保险种', prop: 'insuredTypeId', model: 'insuredTypeId', style: 'ivu-col-span-13', options: 'insuredTypeId', fn: 'getTreatmentParametersEnableList', isDisabled: false },
        { type: 'select', label: '待遇名称：', placeholder: '请选择待遇名称', prop: 'treatmentTypeId', model: 'treatmentTypeId', style: 'ivu-col-span-11', options: 'treatmentParametersEnableList', fn: 'selectChange', isDisabled: false },
        { type: 'input', label: '身份证号：', placeholder: '请输入身份证号', prop: 'employeeIdCardNo', model: 'employeeIdCardNo', style: 'ivu-col-span-13', isDisabled: true },
        { type: 'input', label: '个人编号：', placeholder: '请输入个人编号', prop: 'personalCode', model: 'personalCode', style: 'ivu-col-span-11', isDisabled: false },
        { type: 'select', label: '商保编号：', placeholder: '请选择商保编号', prop: 'socialSecurityId', model: 'socialSecurityId', style: 'ivu-col-span-13', options: 'fundData', fn: 'securityNoChange', isDisabled: true },
        // { type: 'input', label: '城市：', placeholder: '请选择城市', prop: 'areaName', model: 'areaName', style: 'ivu-col-span-11', options: 'areaTree', isDisabled: true },
        { type: 'interval', label: '参保时间：', placeholder1: '开始日期', prop: 'declareDate', prop1: 'add_DeclareDate', model1: 'add_DeclareDate', style: 'ivu-col-span-11 is-required', isDisabled: true },
        { type: 'input', label: '保单金额：', placeholder: '请输入保单金额', prop: 'declareSalary', model: 'declareSalary', style: 'ivu-col-span-13 is-required', isDisabled: true },
        { type: 'fujian', label: '附件下载：', placeholder: '请输入参保基数', prop: 'attachmentList', model: 'attachmentList', options: 'attachmentList', style: 'ivu-col-span-11 is-required', isDisabled: true }
      ],
      
      rules: {
        customerId: [
          { required: true, message: '请选择客户名称', trigger: 'change' }
        ],
        employeeID: [
          { required: true, message: '请选择员工', trigger: 'change' }
        ],
        insuredTypeId: [
          { required: true, message: '请选择参保险种', trigger: 'change' }
        ],
        treatmentTypeId: [
          { required: true, message: '请选择待遇名称', trigger: 'change' }
        ],
        employeeIdCardNo: [
          { required: true, message: '请输入身份证号', trigger: 'change' }
        ],
        personalCode: [
          { required: false, message: '请输入个人编号', trigger: 'change' }
        ],
        socialSecurityId: [
          { required: true, message: '请选择商保编号', trigger: 'change' }
        ]
      },
      arrListDown: {
        tempOps: [],
        fundData: [],
        parametertype: [],
        treatmentParametersEnableList: [],
        employeeList: [],
        attachmentList: []
      },
      isCanSubmit: true,
      queryFundData: [],
      queryEmployeeList: [],
      enumName: '',
      fileList: [],
      rankList:[],
      showTable: false
    }
  },

  mounted () {
  },

  methods: {
    cancel () {
      this.isShowCreateCommercialWagesModal = false
    },

    // 附件下载
    handleDownLoad (row) {
      var url = baseUrl + '/Attachment/Download?id=' + row.id
      window.open(url, '_blank')
    },

    show (actionType, id) {
      this.isCanSubmit = true
      this.actionType = actionType
      console.log('actionType: ', actionType, 'id: ', id)
      this.isShowCreateCommercialWagesModal = true
      this.$refs.formData.resetFields()
      this.rankList = []
      console.log('this.arrListDown: ', this.arrListDown)
    },

    // 监听所有调用的方法
    listenCall (methodsWords, ...values) {
      this[methodsWords](...values)
    },

    // 客户名称改变
    customerIdChange (model, val) {
      console.log('客户名称改变model: ', model, ', val: ', val)
      this.formData.employeeID = null
      if (val) {        
        this.formItem[1].isDisabled = false
        this.getEmployeeListNew(val)
      } else {
        this.formItem[1].isDisabled = true
      }
    },

    // 获取员工下拉内容
    async getEmployeeListNew (id) {
      var params = {
        CompanyID: id,
        BeHiring: 1,
        PageIndex: 1,
        PageSize: 1000
      }
      let res = await TreatmentEnjoyManageApi.getEmployeeList(params)
      console.log('res: ', res)
      if (res.status === 200 && res.data.success && res.data.data.length) {
        this.queryEmployeeList = res.data.data
        this.arrListDown.employeeList = res.data.data.map(item => {
          return { label: item.text, value: item.value }
        })
      } else {
        this.queryEmployeeList = []
        this.arrListDown.employeeList = []
      }
    },

    // 待遇名称改变
    async selectChange (model, val) {
      console.log(model,val)
      if (model === 'treatmentTypeId'){
        this.rankList = []
        this.securityNoChange('socialSecurityId',this.formData.socialSecurityId)
      }
      if (model === 'employeeID') {
        var selectEmployee = this.queryEmployeeList.find(item => {
          return item.value === val
        })
        console.log('selectEmployee: ', selectEmployee)
        if (selectEmployee != undefined) {
          let res = await EmployeesApi.getEmployee({id: selectEmployee.value})
          console.log(res,'getemployee')
          if (res.status === 200 && res.data.success) {
            this.formData.employeeIdCardNo = res.data.data.idCardNo ? res.data.data.idCardNo + '' : ''
          } else {
            this.formData.employeeIdCardNo = ''
          }
        } else {
          this.formData.employeeIdCardNo = ''
        }
      }

      if (model == 'treatmentTypeId' && !val) {
        this.formData.treatmentTypeId = ''
      }

      // if(model == 'treatmentTypeId' && val) {
      //   this.getTreatmentLinkData(val)
      // }

      var params = {
        EmployeeGUID: this.formData.employeeID,
        type: 3
      }
      
      if (this.formData.employeeID && model === 'employeeID') {
        this.formData.socialSecurityId = ''
        this.formData.areaName = ''
        this.formData.add_DeclareDate = ''
        this.formData.reduce_DeclareDate = ''
        this.formData.declareSalary = ''
        this.fileList = []
        let res = await TreatmentEnjoyManageApi.getConfig(params)
        console.log('❤ res: ', res)
        if (res.data.success) {
          const result = res.data.data
          this.arrListDown.fundData = result.map(item => {
            return { label: item.text, value: item.value }
          })
        }
      }
      if (this.formData.employeeID && this.formData.treatmentTypeId) {
        this.formItem[5].isDisabled = false
      } else {
        this.formItem[5].isDisabled = true
      }
    },

    // 商保类型选择改变
    async securityNoChange (model, val) {
      console.log('model: ', model)
      console.log('val: ', val)
      console.log('this.fundData: ', this.fundData)
      var selectObj = this.arrListDown.fundData.find(item => {
        return item.value === val
      })
      console.log('❤ selectObj: ', selectObj)
      console.log('❤ this.formData: ', this.formData)
      if (selectObj) {
        let params = {
          EnjoyType: '3',
          EmployeeId: this.formData.employeeID,
          TreatmentTypeId: this.formData.treatmentTypeId,
          SocialSecurityId: val,
        }
        let res = await TreatmentEnjoyManageApi.getWelfarePercentData(params)
        if (res.status === 200 && res.data.success) {
          console.log('商保类型改变 res: ', res)
          this.formData.areaGUID = res.data.data.areaGUID
          this.formData.areaName = res.data.data.areaAllName
          this.formData.add_DeclareDate = res.data.data.add_DeclareDate
          this.formData.reduce_DeclareDate = res.data.data.reduce_DeclareDate
          this.formData.declareSalary = res.data.data.declareSalary
          this.rankList = res.data.data.treatmentBasicsLinkList
          this.arrListDown.attachmentList = res.data.data.attachmentList ? res.data.data.attachmentList : []
          this.showTable = true
        }
      }
    },

    // 日期选择
    handleChangeDatePicker (model, val) {
      this.formData[model] = val
    },

    // 获取商保待遇名称列表
    async getTreatmentParametersEnableList (val) {
      console.log('getTreatmentParametersEnableList',val)
      this.arrListDown.treatmentParametersEnableList = []
      this.formData.insuredTypeId = val
      this.showTable = false
      if (val) {
        console.log('获取商保待遇名称列表val: ', val)
        console.log('this.arrListDown.parametertype: ', this.arrListDown.parametertype)
        var params = {
          insuredTypeId: val,
          HasPaging: true,
          PageIndex: 1,
          PageSize: 300
        }
        let res = await TreatmentBasicsTypeApi.getBasicsTypeList(params)
        console.log('根据参数类型 获取已启用相关参数列表res: ', res)
        if (res.status === 200 && res.data.success && res.data.data) {
          this.arrListDown.treatmentParametersEnableList = res.data.data.map(item => {
            return { label: item.text, value: item.value }
          })
        }
      }
    },

    // 获取环节getTreatmentLinkData
    async getTreatmentLinkData (id) {
      this.arrListDown.attachmentList = []
      if (id) {
        var params = {
          treatmentTypeId: id
        }
        let res = await TreatmentEnjoyManageApi.getTreatmentLinkData(params)
        console.log('获取环节res: ', res)
        if (res.status === 200 && res.data.success && res.data.data) {
          this.rankList = res.data.data.treatmentBasicsLinkList
          this.arrListDown.attachmentList = res.data.data.attachmentList
        } else {
          this.rankList = []
        }
        this.showTable = true
      }
    },  

    // 保存
    handleSave () {
      this.$refs.formData.validate((valid) => {
        if (valid) {
          this.isCanSubmit = false
          // if (this.formData.declareSalary == 0) {
          //   this.isCanSubmit = true
          //   this.$Message.error('参保基数为0不能享受待遇')
          //   return
          // }
          this.formData.add_DeclareDate = this.$moment(this.formData.add_DeclareDate).format('YYYY-MM-DD') // 开始时间
          this.formData.reduce_DeclareDate = this.$moment(this.formData.reduce_DeclareDate).format('YYYY-MM-DD') // 结束时间
          var params = {...this.formData}
          console.log('❀ params: ', params)
          TreatmentEnjoyManageApi.save(params).then(res => {
            if (res.data.success) {
              this.$Message.success(res.data.message)
              this.isShowCreateCommercialWagesModal = false
              this.$emit('query')
            } else {
              this.isCanSubmit = true
              this.$Message.error({
                content: res.data.message,
                duration: 10,
                closable: true
              })
            }
          })
        }
      })
    }
  }
}
</script>

<style lang="less">
  // .ivu-table-fixed-body{
  //   overflow: visible;
  // }
</style>
